import os,sys
from PyQt4 import QtCore,QtGui
import mldictwindow,mledit,mldictdm

class MLDictApp(QtCore.QObject):
  def __init__(self):
    self.dmName='dict.dat'
    self.dm=mldictdm.MLDictDataModel()
    if os.access(self.dmName,os.R_OK):
      self.dm.LoadDict(self.dmName)
    else:
      self.dm.CreateDict(self.dmName,['English','Telugu'])
    self.app=QtGui.QApplication(sys.argv)
    self.mainWindow=QtGui.QMainWindow()
    self.mainWindow.resize(150,100)
    self.mainWindow.setWindowTitle("Multi-Lingual Dictionary")
    self.mainWindow.show()
    self.setupUI()
    sys.exit(self.app.exec_())

  def setupUI(self):
    self.cusWin=mldictwindow.Ui_MainWindow()
    self.cusWin.setupUi(self.mainWindow)
    self.cusWin.tableWidget.setSortingEnabled(True)
    self.reloadTable()
    QtCore.QObject.connect(self.cusWin.addRemoveLangButton, QtCore.SIGNAL("clicked()"), self.addRemoveLangHandler)
    QtCore.QObject.connect(self.cusWin.addButton,QtCore.SIGNAL("clicked()"),self.addRowHandler)
    QtCore.QObject.connect(self.cusWin.removeButton,QtCore.SIGNAL("clicked()"),self.removeRowHandler)
    QtCore.QObject.connect(self.cusWin.tableWidget,QtCore.SIGNAL("cellChanged(int,int)"),self.cellChanged)
    QtCore.QObject.connect(self.cusWin.searchButton,QtCore.SIGNAL("clicked()"), self.searchHandler)

  def addRemoveLangHandler(self):
    self.addRemDlg=QtGui.QDialog()
    self.addRemUi=mledit.Ui_Dialog()
    self.addRemUi.setupUi(self.addRemDlg)
    self.addRemUi.listWidget.clear()
    for ef in self.dm.getFields():
      newItem=QtGui.QListWidgetItem(QtCore.QString(ef))
      newItem.setFlags(QtCore.Qt.ItemIsEditable|QtCore.Qt.ItemIsSelectable|QtCore.Qt.ItemIsEnabled)
      self.addRemUi.listWidget.addItem(newItem)
    self.addRemDlg.setModal(True)
    QtCore.QObject.connect(self.addRemUi.listWidget,QtCore.SIGNAL("itemChanged(QListWidgetItem*)"),self.fieldNameChangedHandler)
    QtCore.QObject.connect(self.addRemUi.addButton,QtCore.SIGNAL("clicked()"),self.addFieldHandler)
    QtCore.QObject.connect(self.addRemUi.editButton,QtCore.SIGNAL("clicked()"),self.editFieldHandler)
    QtCore.QObject.connect(self.addRemUi.removeButton,QtCore.SIGNAL("clicked()"),self.removeFieldHandler)
    QtCore.QObject.connect(self.addRemUi.closeButton,QtCore.SIGNAL("clicked()"),self.closeDialogHandler)
    self.addRemDlg.show()

  def searchHandler(self):
    self.cusWin.tableWidget.clearSelection()
    searchStr=self.cusWin.searchEdit.text()
    widgetItems=self.cusWin.tableWidget.findItems(searchStr,QtCore.Qt.MatchStartsWith)
    if widgetItems:
      self.cusWin.tableWidget.scrollToItem(widgetItems[0])
      self.cusWin.tableWidget.setCurrentItem(widgetItems[0])

  def addRowHandler(self):
    rowc=self.cusWin.tableWidget.rowCount()
    colc=self.cusWin.tableWidget.columnCount()
    self.cusWin.tableWidget.insertRow(rowc)
    rowId=self.dm.getNextRowId()
    rec=self.dm.CreateRecord()
    rec.RID=rowId
    self.dm.InsertValues([rec])
    tw=QtGui.QTableWidgetItem(QtCore.QString(str(rowId)))
    tw.setFlags(QtCore.Qt.ItemIsSelectable|QtCore.Qt.ItemIsEditable|QtCore.Qt.ItemIsEnabled)
    self.cusWin.tableWidget.setItem(rowc,0,tw)
    for ec in range(1,colc):
      tw=QtGui.QTableWidgetItem(QtCore.QString(""))
      tw.setFlags(QtCore.Qt.ItemIsSelectable|QtCore.Qt.ItemIsEditable|QtCore.Qt.ItemIsEnabled)
      self.cusWin.tableWidget.setItem(rowc,ec,tw)
    pass

  def cellChanged(self,row,col):
    col_count=self.cusWin.tableWidget.columnCount()
    rec=self.dm.CreateRecord()
    for ec in range(col_count):
      widget=self.cusWin.tableWidget.horizontalHeaderItem(ec)
      if widget:
        fieldName=widget.text()
        if self.cusWin.tableWidget.item(row,ec):
          setattr(rec,str(fieldName),str(self.cusWin.tableWidget.item(row,ec).text()))
    self.dm.UpdateValues([rec])

  def removeRowHandler(self):
    cur_row=self.cusWin.tableWidget.currentRow()
    rec=self.dm.CreateRecord()
    rec.RID=str(self.cusWin.tableWidget.item(cur_row,0).text())
    self.dm.RemoveValues([rec])
    self.cusWin.tableWidget.removeRow(cur_row)

  def updateFields(self):
    fields=self.dm.getFields()
    itemCount=self.addRemUi.listWidget.count()
    for idx in range(itemCount):
      item=self.addRemUi.listWidget.item(idx)
      if item.text() not in fields:
        self.dm.AddField(str(item.text()))
      elif item.text() in fields:
        fields.remove(str(item.text()))
    for ef in fields:
      self.dm.RemoveField(ef)
    self.reloadTable()

  def clearTable(self):
    self.cusWin.tableWidget.clear()
    self.cusWin.tableWidget.clearContents()
    # removing all rows
    row_count=self.cusWin.tableWidget.rowCount()
    for er in range(row_count):
      self.cusWin.tableWidget.removeRow(0)
    col_count=self.cusWin.tableWidget.columnCount()
    for ec in range(col_count):
      self.cusWin.tableWidget.removeColumn(0)

  def reloadTable(self):
    self.cusWin.tableWidget.setSortingEnabled(False)
    self.clearTable()
    fields=self.dm.getPersistedFields()
    tblLabels=QtCore.QStringList()
    for ef in fields:
      tblLabels.append(QtCore.QString(ef))
    self.cusWin.tableWidget.setColumnCount(len(fields))
    self.cusWin.tableWidget.setHorizontalHeaderLabels(tblLabels)
    dictvals=self.dm.GetValues()
    if dictvals:
      for ev in dictvals:
        row_count=self.cusWin.tableWidget.rowCount()
        self.cusWin.tableWidget.insertRow(row_count)
        idx=0
        for ef in dir(ev):
          if callable(ef) or ef.startswith('__'): continue
          val=getattr(ev,ef)
          if val==None:
            tblItem=QtGui.QTableWidgetItem(QtCore.QString(""))
          elif ef=='RID': 
            tblItem=QtGui.QTableWidgetItem(QtCore.QString(str(val)))
          else:
            tblItem=QtGui.QTableWidgetItem(QtCore.QString(str(val)))
          tblItem.setFlags(QtCore.Qt.ItemIsSelectable|QtCore.Qt.ItemIsEditable|QtCore.Qt.ItemIsEnabled)
          self.cusWin.tableWidget.setItem(row_count,fields.index(ef),tblItem)
          idx+=1
    self.cusWin.tableWidget.setSortingEnabled(True)

  def fieldNameChangedHandler(self,widgetItem):
    pass

  def addFieldHandler(self):
    newItem=QtGui.QListWidgetItem("")
    newItem.setFlags(QtCore.Qt.ItemIsEditable|QtCore.Qt.ItemIsSelectable|QtCore.Qt.ItemIsEnabled)
    self.addRemUi.listWidget.addItem(newItem)
    self.addRemUi.listWidget.editItem(newItem)

  def editFieldHandler(self):
    if self.addRemUi.listWidget.currentItem():
      self.addRemUi.listWidget.editItem(self.addRemUi.listWidget.currentItem())

  def removeFieldHandler(self):
    if self.addRemUi.listWidget.currentItem():
      self.addRemUi.listWidget.takeItem(self.addRemUi.listWidget.currentRow())

  def closeDialogHandler(self):
    self.addRemDlg.hide()
    self.updateFields()

if __name__=='__main__':
  mainApp=MLDictApp()

# end-of-script
